import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
nprogress.configure({ showSpinner: false })

// 获取用户相关的小仓库内部token数据，去判断用户是否登陆成功
import pinia from './store'
import useUserStore from './store/modules/user'
import type { UserState } from './store/modules/types'
import setting from './setting'
// 在组件的外部，如果通过同步的语句获取仓库是获取不到的，因为获取小仓库的前提是必须要有大仓库
const userStore: UserState = useUserStore(pinia)

router.beforeEach(async (to: any, _from: any, next: any) => {
  nprogress.start()
  const token = userStore.token
  const username = userStore.username
  document.title = setting.title + '-' + to.meta.title

  if (token) {
    // 用户登陆
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 发起获取用户信息请求，保证每次切换路由都有用户信息
      if (username) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next()
        } catch (error) {
          // token过期或手动修改token
          await userStore.useLogout()
          next({
            path: '/login',
            query: {
              redirect: to.path,
            },
          })
        }
      }
    }
  } else {
    // 用户未登陆
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

router.afterEach((_to: any, _from: any, _next: any) => {
  nprogress.done()
})
